<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 模板里面写了@  那么webpack 会自动编译打包处理 -->
      <!-- <img src="@/assets/common/bigUserHeader.png" alt=""> -->
      <!-- 不能将 图片路径写在变量里面，然后绑定变量 -->
      <!-- <img :src="userPhoto" alt=""> -->
      <!-- 工具条 -->
      <page-tools>
        <span slot="before">共{{ page.total }}条数据</span>
        <div slot="after">
          <el-button size="small" icon="el-icon-upload2" type="success" :disabled="!checkPermission('point-employees-add')" @click="$router.push('/import')">导入员工</el-button>
          <el-button size="small" icon="el-icon-download" type="warning" @click="exportData">导出员工</el-button>
          <el-button size="small" icon="el-icon-plus" type="primary" :disabled="!checkPermission('point-employees-add')" @click="$refs.addEmployee.showDialog=true">新增员工</el-button>
        </div>
      </page-tools>
      <!-- 表格内容 -->
      <el-card>
        <!-- 【列表第4步】 -->
        <el-table border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="">
            <template slot-scope="{row}">
              <el-input v-model="row.username" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <!-- 图片列 -->
          <el-table-column label="照片" width="120">
            <template slot-scope="{ row }">
              <!-- {{ row.staffPhoto }} -->
              <!-- <img v-imageerror="userPhoto" style="width:100px;" :src="row.staffPhoto" alt=""> -->
              <img v-imageerror="require('@/assets/common/bigUserHeader.png')" style="width:100px;" :src="row.staffPhoto" alt="" @click="showCodeImg(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="聘用形式" :formatter="showHireType" prop="formOfEmployment" sortable="">
            <!-- <template slot-scope="{ row }"> -->
            <!-- 渲染 自定义内容 -->
            <!-- <span v-if="row.formOfEmployment==1">正式</span>
              <span v-if="row.formOfEmployment==2">非正式</span> -->
            <!-- {{ showHireType(row) }} -->
            <!-- </template> -->
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template v-slot="{row}">
              <el-switch :value="row.enableState*1 === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" :disabled="!checkPermission('point-employees-edit')" @click="$router.push(`/employees/detail/`+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('point-employees-delete')" @click="delRole(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination background :page-sizes="[10,20,30,40]" :current-page="page.page" :page-size="page.size" :total="page.total" layout="sizes,prev, pager, next" @current-change="pageChange" @size-change="sizeChange" />
        </el-row>
      </el-card>
    </div>
    <!-- 增加/修改弹框 -->
    <add-employee ref="addEmployee" />

    <!-- 二维码弹框 -->
    <el-dialog
      title="二维码"
      :visible.sync="showDialog"
      width="30%"
    >
      <canvas id="canvas" ref="canvas" />
    </el-dialog>

    <!-- 授权角色 -->
    <assign-role ref="role" />

  </div>
</template>
<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import employeesConstant from '@/constant/employees'
import AddEmployee from './components/add-employee'
import { formatDate } from '@/filters'
import Qrcode from 'qrcode'
import AssignRole from './components/assign-role'
export default {
  name: 'Employess',
  components: {
    AddEmployee, AssignRole
  },
  data() {
    return {
      // 【列表第1步】 定义变量
      list: [], // 表格数据
      page: { // 页码相关
        page: 1,
        size: 10,
        total: 0
      },
      showDialog: false
      // userPhoto: '@/assets/common/bigUserHeader.png'
      // userPhoto: require('@/assets/common/bigUserHeader.png')

    }
  },
  created() {
    // 【列表第3步】
    this.getEmployeesList()
  },
  methods: {
    // 【列表第2步】  获取员工列表方法
    async getEmployeesList() {
      // 2.1 发送请求
      const { total, rows } = await getEmployeesList(this.page)
      // 2.2 赋值
      this.page.total = total
      this.list = rows
    },
    // 页码更换事件
    pageChange(newPage) {
      this.page.page = newPage
      this.getEmployeesList()
    },
    // 每页数量更换
    sizeChange(newSize) {
      this.page.size = newSize
      this.getEmployeesList()
    },
    // 正确显示聘用形式
    showHireType(val) {
      const result = employeesConstant.hireType.find(item => item.id * 1 === val.formOfEmployment * 1)
      return result ? result.value : '未知'
    },
    // 删除角色
    async delRole(id) {
      try {
        await this.$confirm('确定删除吗?')
        await delEmployee(id)
        if (this.page.page !== 1 && this.list.length === 1) {
          this.page.page--
        }
        this.$message.success('删除成功')
        this.getEmployeesList()
      } catch (error) {
        console.log(error)
      }
    },
    // 导出员工数据
    exportData() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 1. 找到所有要导出的员工数据
        const { rows } = await getEmployeesList({ page: 1, size: this.page.total })
        // 2. 准备表头数据
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        excel.export_json_to_excel({
          header: Object.keys(headers), // 常规表头
          multiHeader: [['姓名', '基本信息', '', '', '', '', '部门']], // 复杂表头
          merges: ['A1:A2', 'B1:F1', 'G1:G2'], // 合并
          data: this.formatJson(headers, rows), // 表数据
          filename: '员工信息记录' // 文件名称
        })
      })
      // 使用了import函数导入
      // import xx from 'xxx'
      // import('xxx')  返回一个Promise对象
      // import('@/vendor/Export2Excel').then(excel => {
      //   // excel 就是模块信息
      //   // 导入json数据给excel表格
      //   excel.export_json_to_excel({
      //     // 表头
      //     header: ['姓名', '年龄'],
      //     // 表数据
      //     data: [['张三', 20], ['里斯', 22], ['王五', 33]],
      //     // 文件名称
      //     filename: '测试'
      //   })
      // })
    },
    // 整理表格的数据
    formatJson(headers, rows) {
      // 表格需要的表头是 Object.keys(headers)
      // 需要的结构：[['张三', '18868816185'],['里斯', '18868816185'],['王五', '18868816185']]
      // 目前的结构：[{ username:'张三',mobile: 18868816185},{ username:'里斯',mobile: 18868816185},{ username:'王五',mobile: 18868816185}]
      return rows.map(item => {
        // item 是什么==> { username:'张三',mobile: 18868816185}
        // Object.keys(headers) ==> [姓名,手机号,入职日期,....]
        return Object.keys(headers).map(key => {
          // headers[key] 汉字对应的英文
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]) // 返回格式化之前的时间
          } else if (headers[key] === 'formOfEmployment') {
            var en = employeesConstant.hireType.find(obj => obj.id === item[headers[key]])
            return en ? en.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    // 显示二维码
    showCodeImg(url) {
      if (!url) return this.$message.warning('没有图片信息')
      this.showDialog = true
      // 生成二维码
      // Qrcode.toCanvas(canvasDOM节点，字符串(要转换的内容),回调函数)
      // 等到弹框渲染完成，里面的内容全部渲染好了
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.canvas, url)
      })
    },
    // 修改角色
    editRole(id) {
      // 调用组件内获取所有角色的方法
      this.$refs.role.getRoleList()
      // 调用组件内获取点击的用户信息的方法，传入用户id
      this.$refs.role.getUserInfo(id)
      // 打开弹框
      this.$refs.role.showDialog = true
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
